package com.example.demo.model.entity.user;

import com.example.demo.model.enums.UserStatus;
import com.example.demo.model.enums.UserTypeEnum;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import java.time.LocalDateTime;
import java.util.Collection;
import java.util.Collections;

@Data
public class User {

    private Long userId;
    private String username;
    private String password;
    private String name;
    private String email;
    private String phone;
    private UserTypeEnum userType; // 原错误: = UserTypeEnum.STUDENT;
    private Integer status;        // 原错误: = UserStatus.ENABLED.getCode();
    private String avatar;         // 原错误: = "default-avatar.jpg"
    private LocalDateTime createTime;
    private LocalDateTime updateTime;

    // ========== 安全方法 ==========
    public Collection<? extends GrantedAuthority> getAuthorities() {
        String role = userType.name(); // 去掉 ROLE_ 前缀
        return Collections.singletonList(new SimpleGrantedAuthority(role));
    }

    public Long getId(){
        return userId;
    }

    public void setId(Long id){
        userId = id;
        return;
    }

    public boolean isAccountNonExpired() {
        return true;
    }

    public boolean isAccountNonLocked() {
        return UserStatus.ENABLED.getCode() == status;
    }

    public boolean isCredentialsNonExpired() {
        return true;
    }

    public boolean isEnabled() {
        return UserStatus.ENABLED.getCode() == status;
    }

    // ========== 类型判断 ==========
    public boolean isAdmin() {
        return UserTypeEnum.ADMIN.equals(userType);
    }

    public boolean isTeacher() {
        return UserTypeEnum.TEACHER.equals(userType);
    }

    public boolean isStudent() {
        return userType == null || UserTypeEnum.STUDENT.equals(userType);
    }

    // ========== 数据完整性保护 ==========
    public void validateDataIntegrity() {
        if (userType == null) {
            userType = UserTypeEnum.STUDENT;
        }
        if (status == null) {
            status = UserStatus.ENABLED.getCode();
        }
        if (avatar == null) {
            avatar = "default-avatar.jpg";
        }
    }
}